﻿using Max.Ph5_2009A.NewShopping.DTO;
using Max.Ph5_2009A.NewShopping.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Max.Ph5_2009A.NewShopping.API.Controllers.Product
{
    /// <summary>
    /// 产品控制器
    /// </summary>
    [Route("product/info")]
    [ApiController]
    public class ProductInfoController : ControllerBase
    {
        //图片、商品名称、价格、店铺名称、评价数
        static List<ProductInfoOutputDto> dataScource = new List<ProductInfoOutputDto>();

        IProductSKUService _service;
        IProductSKUImageService _imageService;

        IProductInfoService _productInfoService;
        ICategoryInfoService _categoryInfoService;
        ICategorySpecInfoService _categorySpecInfoService;
        ICategorySpecValueService _categorySpecValueService;
        ISpecInfoService _specInfoService;

        /// <summary>
        /// 构造函数（作用：初始化值）
        /// </summary>
        public ProductInfoController(IProductSKUService service, IProductSKUImageService imageService,
            IProductInfoService productInfoService,
            ICategoryInfoService categoryInfoService,
            ICategorySpecInfoService categorySpecInfoService,
            ICategorySpecValueService categorySpecValueService,
            ISpecInfoService specInfoService
            )
        {
            _service = service;
            _imageService = imageService;

            _productInfoService = productInfoService;
            _categoryInfoService = categoryInfoService;
            _categorySpecInfoService = categorySpecInfoService;
            _specInfoService = specInfoService;
            _categorySpecValueService = categorySpecValueService;

            if (dataScource.Count <= 0)
            {
                for (int i = 0; i < 100; i++)
                {
                    ProductInfoOutputDto p = new ProductInfoOutputDto
                    {
                        Id = Guid.NewGuid(),
                        Name = $"商品名称{i}",
                        ImageUrl = $"images/product/lx{new Random().Next(1, 5)}.png",
                        StoreName = $"店铺名称{new Random().Next(1, 2)}",
                        Price = (i + 1) * new Random().Next(10, 20),
                        CommentNumber = ((i + 1) * new Random().Next(10, 20)).ToString(),
                        SaleNumber = i + 1
                    };

                    dataScource.Add(p);
                }
            }
        }




        #region 活数据
        /// <summary>
        /// 获取所有的商品数据
        /// </summary>
        /// <param name="key"></param>
        /// <param name="sortField"></param>
        /// <param name="sortValue"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Select(string key, string sortField, string sortValue, int pageIndex, int pageSize)
        {
            ResponseResultOutputDto dto = new();

            #region 参数判断

            if (pageIndex <= 0)
            {
                pageIndex = 1;
            }
            if (pageSize <= 0)
            {
                pageSize = 12;
            }
            key ??= ""; //如果key = null，那么将""这个值赋值给key，否则就用key原值

            sortField ??= "id";
            sortValue ??= "asc";

            #endregion

            #region 调用业务

            //if (sortField.ToLower().Equals("price"))
            //    _service.Select(x => x.Name.Contains(key), x => x.Price, sortValue.ToLower().Equals("asc") ? true : false, pageIndex, pageSize, out int total);

            //else if(sortField.ToLower().Equals("sale"))
            //    _service.Select(x => x.Name.Contains(key), x => x.SaleNumber, sortValue.ToLower().Equals("asc") ? true : false, pageIndex, pageSize, out int total);

            var list = _service.Select(x => x.Name.Contains(key), x => x.SaleNumber, sortValue.ToLower().Equals("asc") ? true : false, pageIndex, pageSize, out int total);

            //需要将源数据转换为DTO == 什么是DTO？ == 数据传输对象

            var q = from a in list
                    select new ProductInfoOutputDto
                    {
                        Id = a.Id,
                        ImageUrl = _imageService.Select().Where(x => x.ProductSKUId == a.Id).FirstOrDefault().ImagePath ?? "images/product/lx1.png",
                        Name = a.Name,
                        Price = (decimal)a.SalePrice,
                        SaleNumber = a.SaleNumber,
                        StoreName = "没有店铺"
                    };


            dto.Data = new { items = q, total };
            #endregion

            return Ok(dto);
        }

        /// <summary>
        /// 根据ID获取商品详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("id")]
        public IActionResult SelectInfoById(string id)
        {
            ResponseResultOutputDto dto = new();

            #region 参数判断

            if (string.IsNullOrEmpty(id))
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = "参数错误";
                return BadRequest(dto);
            }
            #endregion

            #region 业务调用
            //商品的主信息（自身的信息）
            var model = _service.Select().Where(x => x.Id.ToString().Equals(id)).FirstOrDefault();
            if (model == null)
            {
                dto.Code = Domain.Shared.ResponseResultStateCode.系统错误;
                dto.Message = "非法请求";
                return BadRequest(dto);
            }

            //商品的相关信息（这款商品的规格【如：颜色、尺寸等】、图片列表、评论列表）
            /*
             * 根据商品SKUID，找到分类ID
             * 根据分类ID，找到这个分类有哪些规格
             * 然后规格，找到具体规格对应的值有哪些
             * >>找到分类 --- 手机游戏
             * >>根据分类找到规格 --- 颜色和内存
             * >>颜色有哪些值：彩金、银灰、粉色
             * >>内存有哪些值：128G、256G、512G、1TB
             * **/

            //根据传过来的商品Id，获取这个商品的SPU
            var p = _productInfoService.Select().Where(x => x.Id == model.ProductId).FirstOrDefault();
            //根据spu的分类，去获取这个分类的规格(分类对应的规格有很，我们也不知道有多少个)
            var specs = _categorySpecInfoService.Select().Where(x => x.CategoryId == p.CategoryId);
            //根据分类规格id，去找这个规格下面具体有哪些值

            var ts = _categorySpecValueService.Select();
            var sps = _specInfoService.Select();
            var q = from a in specs
                    join b in sps on a.SpecId equals b.Id
                    select new
                    {
                        a.SpecId, //规格的id
                        b.Name, //规格名称
                        items = ts.Where(x => x.CategorySpecId == a.Id).ToList() //规格对应的规格值
                    };

            dto.Data = new { 
                self = model,  //自身本的信息
                images = "",  //图片集信息
                specs = q,  //规格信息
                comments = ""  //评论信息
            };
            #endregion

            return Ok(dto);
        }

        #endregion


        #region 静态数据

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>

        private IActionResult _Query(string? key, string? sortField, string? sortValue, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0)
                pageIndex = 1;

            if (pageSize <= 0)
                pageSize = 10;

            //if (string.IsNullOrEmpty(sortField))
            //    sortField = "id";
            //if (string.IsNullOrEmpty(sortValue))
            //    sortValue = "asc";

            key ??= ""; //null ""
            sortField ??= "id";  //这一行，是下面一行的简化写法
            sortValue = sortValue ?? "asc";

            ResponseResultOutputDto dto = new();

            //调业务
            var newDataSource = dataScource.Where(x => x.Name.Contains(key));
            var total = newDataSource.Count();

            List<ProductInfoOutputDto> list = new List<ProductInfoOutputDto>();
            #region 排序

            //根据销量
            if (sortField.ToLower().Equals("sale"))
            {
                if (sortValue.ToLower().Equals("asc"))
                {
                    list = newDataSource.OrderBy(x => x.SaleNumber).ToList();
                }
                else
                {
                    list = newDataSource.OrderByDescending(x => x.SaleNumber).ToList();
                }
            }
            else if (sortField.ToLower().Equals("price"))
            {
                if (sortValue.ToLower().Equals("asc"))
                {
                    list = newDataSource.OrderBy(x => x.Price).ToList();
                }
                else
                {
                    list = newDataSource.OrderByDescending(x => x.Price).ToList();
                }
            }
            else
            {
                if (sortValue.ToLower().Equals("asc"))
                {
                    list = newDataSource.OrderBy(x => x.Id).ToList();
                }
                else
                {
                    list = newDataSource.OrderByDescending(x => x.Id).ToList();
                }
            }
            #endregion

            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();

            dto.Data = new { item = list, total = total };

            return Ok(dto);
        }

        /// <summary>
        /// 获取一条商品数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        private IActionResult QueryById(string id)
        {
            ResponseResultOutputDto dto = new();

            var model = dataScource.Where(x => x.Id.ToString().Equals(id)).FirstOrDefault();

            ProductDetailOutputDto detail = new();
            //这是这条数据（商品）本身拥有的信息
            detail.Name = model.Name;
            detail.Price = model.Price;
            detail.Color = "红";
            detail.Size = "256G";


            //这个商品相关的信息
            detail.Images = new List<string> { "lx1.png", "lx2.png", "lx3.png" };
            detail.Colors = new List<string> { "赤", "橙", "红" };
            detail.Sizes = new List<string> { "128G", "256G", "512G" };
            detail.CommentList = new List<CommentInfoOutputDto>();

            dto.Data = detail;
            return Ok(dto);
        }

        #endregion

        #region 图片上传

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Upload()
        {
            //1、获取用户选择图片或文件
            //IFormFile a = HttpContext.
            var files = Request.Form.Files;
            if(files == null || files.Count<=0)
            {
                return BadRequest("没有选择文件");
            }
            var file = files[0];

            //大小(不能超过1M)
            var size = file.Length;
            //1M * 1024KB * 1024 byte
            //1G = 1024M,1M = 1024KB, 1KB = 1024btye
            var target = 1 * 1024 * 1024;
            if (size > target)
            {
                return BadRequest("文件超出1M");
            }

            //文件格式（只是.jpg文件，其它任何都不行）
            var ext = System.IO.Path.GetExtension(file.FileName);//获取这个文件的扩展名
            //string[] exts = { "jpg", "gif", "png", "jpeg" };
            if (!file.FileName.EndsWith(".jpg"))
            {
                return BadRequest("文件必须是.jpg");
            }

            //重命名
            string newName = Guid.NewGuid().ToString("N"); //把guid中的短线去掉了
            //newName = System.DateTime.Now.ToString("yyyyMMddHHmmss");
            var newFileName = $"{newName}.jpg";

            //文件保存的路径
            var path = "wwwroot/temp/" + newFileName;

            //将文件保存到这个路径下
            using (var stream = System.IO.File.Create(path))
            {
                file.CopyTo(stream);
            }

            return Ok(path);
        }

        #endregion

    }
}
